package com.gable.report.service.impl;

import com.gable.report.common.util.ReturnResultUtil;
import com.gable.report.common.util.UUIDGenerator;
import com.gable.report.dao.IParameterDao;
import com.gable.report.dao.ParameterEventDao;
import com.gable.report.dao.ParameterEventResultDao;
import com.gable.report.model.*;
import com.gable.report.service.ParameterService;
import com.gable.report.util.StringUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gable on 2018/8/28.
 */
@Service
public class ParameterServiceImpl implements ParameterService {

    @Autowired
    IParameterDao parameterDao;

    @Autowired
    ParameterEventDao eventDao;

    @Autowired
    ParameterEventResultDao eventResultDao;

    @Override
    public Map<String, Object> queryParameterDimension(ParameterQuery query) throws Exception {
        Map<String,Object> returnMap = new HashMap<>();
        Map<String,Object> paramMap = new HashMap<>();
        //获取参数异常设备 对应参数组
        if(query.getParameterName().indexOf("电压") > 1 || query.getParameterName().indexOf("电流") > 1){
            paramMap.put("parameterNameA","%电压%");
            paramMap.put("parameterNameB","%电流%");
        }else{
            paramMap.put("parameterNameA","%温度%");
            paramMap.put("parameterNameB","%湿度%");
        }
        paramMap.put("assetsId",query.getAssetsId());
        //获取参数组标准值
        List<ParameterDimensionView> list = parameterDao.queryParameterLevel(paramMap); //获取参数组标准值
        paramMap.put("type",query.getType());   //维度参数
        //查询对应维度参数组的最近20个分析点
        for(ParameterDimensionView view : list){
            paramMap.put("parameterId" ,view.getParameterId());
            List<ParameterDimension> subList = parameterDao.queryParameterDimensionList(paramMap);
            for(ParameterDimension obj : subList){
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(obj.getDimensionTime());
                switch (query.getType()){
                    case 1 :
                        obj.setTime(new SimpleDateFormat("MM-dd HH时").format(date));
                        break;
                    case 2:
                        obj.setTime(new SimpleDateFormat("MM-dd").format(date));
                        break;
                    default:
                        obj.setTime(new SimpleDateFormat("yyyy-MM").format(date));
                }
            }
            Collections.reverse(subList); //倒序排列
            view.setParameterDimensionList(subList);
        }
        returnMap.put("list",list);
        return returnMap;
    }

    @Override
    public Map<String, Object> queryOtherParameterInfoList(String otherEventIds) {
        Map<String,Object> returnMap = new HashMap<>();
        List<ParameterEventAssetsView> returnList = null;
        if(!StringUtil.isEmpty(otherEventIds)){
            List list =  Arrays.asList(otherEventIds.split(","));
            returnList = parameterDao.queryOtherParameterInfoList(list);
        }
        returnMap.put("list",returnList);
        return returnMap;
    }

    @Override
    public Map<String, Object> queryLiveParameter(ParameterQuery query) {
        Map<String,Object> returnMap = new HashMap<>();
        Map<String,Object> paramMap = new HashMap<>();
        //获取参数异常设备 对应参数组
        if(query.getParameterName().indexOf("电压") > -1 || query.getParameterName().indexOf("电流") > -1){
            paramMap.put("parameterNameA","%电压%");
            paramMap.put("parameterNameB","%电流%");
        }else{
            paramMap.put("parameterNameA","%温度%");
            paramMap.put("parameterNameB","%湿度%");
        }
        paramMap.put("assetsId",query.getAssetsId());
        //获取参数组标准值
        List<ParameterDimensionView> list = parameterDao.queryParameterLevel(paramMap); //获取参数组标准值
        paramMap.put("parameterName",query.getParameterName());
        paramMap.put("endTime",query.getCreateTime());
        //查询设备异常参数的正常范围
        for(ParameterDimensionView view : list){
            if(view.getName().equals(query.getParameterName())){
                paramMap.put("minLevelValue",view.getMinLevelValue());
                paramMap.put("maxLevelValue",view.getMaxLevelValue());
                break;
            }
        }
        //查询上次正常时间
        String startTime = parameterDao.queryLastNormalTime(paramMap);
        paramMap.put("startTime",startTime);
        //查询实时参数
        for(ParameterDimensionView view : list){
            paramMap.put("parameterId" ,view.getParameterId());
            List<ParameterDimension> subList = parameterDao.queryLiveParameterList(paramMap);
            view.setParameterDimensionList(subList);
        }

        returnMap.put("list",list);
        return returnMap;
    }

    @Override
    public ReturnResultUtil queryParameterEventAssetsInfo(ParameterHandleView handleView) {
        Map<String,Object> paramMap = new HashMap<>();
        ParameterEventAssetsView assetsView = parameterDao.queryParameterEventAssetsInfo(handleView.getParameterEventId());
        paramMap.put("parameterEventId",handleView.getParameterEventId());  //事件id
        paramMap.put("endTime",handleView.getCreateTime()); //事件发生时间
        if(handleView.getWebSocket()){
            //该设备事件表的所有参数
            List<Long> parameterIdList = parameterDao.queryParameterIdList(paramMap);
            //剔除已知的异常参数
            Iterator<Long> it = parameterIdList.iterator();
            while (it.hasNext()) {
                Long parameterId = it.next();
                if(parameterId.longValue() == handleView.getParameterId().longValue()){
                    it.remove();
                }
            }
            //其他异常参数数量
            Long otherParameterNum = 0L;
            String otherEventsIds = "";
            //其他参数异常事件id集合(供后面查询使用)
            List<Long> otherParameterList = new ArrayList<>();
            //排除参数正常的事件
            paramMap.put("policeLevel",1);
            //该设备事件表的所有参数
            for(Long parameterId : parameterIdList){
                paramMap.put("parameterId",parameterId);
                //该设备该参数的上次正常或者关闭时间
                String startTime = parameterDao.queryLastNormalEventTime(paramMap);
                paramMap.put("startTime",startTime);
                //查询其他异常事件参数id
                Long otherParameterId= parameterDao.queryOtherParameterId(paramMap);
                if(otherParameterId != null){
                    otherParameterNum ++; //统计
                }
                List<Long> eventIdList = parameterDao.queryEventIdList(paramMap);
                otherParameterList.addAll(eventIdList);
            }
            //拼接所有其他参数异常事件的id
            if(otherParameterList.size() > 0){
                for(Long eventId : otherParameterList){
                    otherEventsIds  =  otherEventsIds + eventId + ",";
                }
            }
            if(!"".equals(otherEventsIds)){
                otherEventsIds = otherEventsIds.substring(0,otherEventsIds.lastIndexOf(","));
            }
            assetsView.setOtherParameterNum(otherParameterNum);
            assetsView.setOtherEventIds(otherEventsIds);
        }
        //异常参数的历史记录
        paramMap.put("parameterId",handleView.getParameterId());
        paramMap.put("startTime",null);
        paramMap.put("policeLevel",null);
        //该参数的历史事件id(包含当前事件)
        List<Long> eventIdList = parameterDao.queryEventIdList(paramMap);
        //剔除当前发生的事件id
        Iterator<Long> it = eventIdList.iterator();
        while (it.hasNext()) {
            Long eventId = it.next();
            if (eventId.longValue() == handleView.getParameterEventId().longValue()) {
                it.remove();
            }
        }
        if(eventIdList.size() > 0){
            List<ParameterEventAssetsView> historyList = parameterDao.queryOtherParameterInfoList(eventIdList);
            assetsView.setHistoryList(historyList);
        }

        return new ReturnResultUtil(1,"查询成功",assetsView);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResultUtil handle(ParameterHandleView handleView) throws Exception{
        Map<String,Object> paramMap = new HashMap<>();
        List<Long> list = new ArrayList<>();
        ParameterEvent parameterEvent = new ParameterEvent();
        parameterEvent.setId(handleView.getParameterEventId());
        parameterEvent.setStatus(handleView.getStatus());
        if(handleView.getStatus() == 38001){
            eventDao.updateByPrimaryKeySelective(parameterEvent);
            return new ReturnResultUtil(1,"操作成功",handleView.getStatus());
        }else{
            Long parameterEventResultId = UUIDGenerator.getUniqueLong();
            //推送的合并处理
            if(handleView.getWebSocket()){
                paramMap.put("parameterEventId",handleView.getParameterEventId());  //事件id
                paramMap.put("endTime",handleView.getCreateTime()); //事件发生时间
                //该设备事件表的所有参数
                List<Long> parameterIdList = parameterDao.queryParameterIdList(paramMap);
                for(Long parameterId : parameterIdList){
                    paramMap.put("parameterId",parameterId);
                    //该设备该参数的上次正常或者关闭时间
                    String startTime = parameterDao.queryLastNormalEventTime(paramMap);
                    paramMap.put("startTime",startTime);
                    //截至到上次正常或者关闭时间的所有事件
                    List<Long> eventIdList = parameterDao.queryEventIdList(paramMap);
                    //该设备所有参数的所有事件
                    list.addAll(eventIdList);
                }
                for(Long eventId : list){
                    ParameterEventResult eventResult = new ParameterEventResult();
                    BeanUtils.copyProperties(eventResult,handleView);
                    eventResult.setParameterEventId(eventId);
                    eventResult.setRemark(eventResult.getRemark() + "(运营管理合并处理)");
                    if(eventId.longValue() == handleView.getParameterEventId().longValue()){
                        eventResult.setId(parameterEventResultId);
                    }else{
                        eventResult.setId(UUIDGenerator.getUniqueLong());
                    }
                    ParameterEvent parameterEventIn = new ParameterEvent();
                    parameterEventIn.setId(eventId);
                    parameterEventIn.setStatus(handleView.getStatus());
                    eventDao.updateByPrimaryKeySelective(parameterEventIn);
                    eventResultDao.insertSelective(eventResult);
                }
            //历史记录单个处理
            }else{
                ParameterEventResult eventResult = new ParameterEventResult();
                BeanUtils.copyProperties(eventResult,handleView);
                eventResult.setId(parameterEventResultId);
                eventResult.setRemark(eventResult.getRemark() + "(运营管理提交处理)");
                eventDao.updateByPrimaryKeySelective(parameterEvent);
                eventResultDao.insertSelective(eventResult);
            }

            return new ReturnResultUtil(1,"操作成功",parameterEventResultId);
        }
    }

}
